﻿@model IList<ProductDetailsModel.ProductAttributeModel>
@using Nop.Web.Models.Catalog;
@using Nop.Core.Domain.Catalog;
@using Nop.Core.Infrastructure;
@using System.Text;
@using System.Globalization;
@using Nop.Services.Security;
@if (Model.Count > 0)
{
    //dynamic price update support
    var hidePrices = !EngineContext.Current.Resolve<IPermissionService>().Authorize(StandardPermissionProvider.DisplayPrices);
    var dynamicPriceUpdate = EngineContext.Current.Resolve<CatalogSettings>().EnableDynamicPriceUpdate;
    var dynamicPriceUpdateAjax = EngineContext.Current.Resolve<CatalogSettings>().DynamicPriceUpdateAjax;
    var priceAdjustmentTableScripts = new StringBuilder();
    var priceAttributeScripts = new StringBuilder();

    var productId = Model.Any() ? Model.First().ProductId : 0;
    var priceAdjustmentTableName = string.Format("priceAdjustmentTable_{0}", productId);
    var priceAdjustmentFuncName = string.Format("adjustPrice_{0}", productId);
    if (dynamicPriceUpdate && !hidePrices)
    {
        foreach (var attribute in Model)
        {
            string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id);


            switch (attribute.AttributeControlType)
            {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                    {
                        foreach (var attributeValue in attribute.Values)
                        {
                            //<tianyingchun> move it into swip attribute item styles logics.
                            priceAdjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0}['{1}_{2}'] = {3};\n", priceAdjustmentTableName, controlId, attributeValue.Id, (float)attributeValue.PriceAdjustmentValue);
                            //priceAttributeScripts.AppendFormat("$('#{0}_{1}').click(function(){{{2}($);}});\n", controlId, attributeValue.Id, priceAdjustmentFuncName);
                        }
                    }
                    break;
                case AttributeControlType.Checkboxes:
                case AttributeControlType.ReadonlyCheckboxes:
                    {
                        foreach (var attributeValue in attribute.Values)
                        {
                            priceAdjustmentTableScripts.AppendFormat(CultureInfo.InvariantCulture, "{0}['{1}_{2}'] = {3};\n", priceAdjustmentTableName, controlId, attributeValue.Id, (float)attributeValue.PriceAdjustmentValue);
                            priceAttributeScripts.AppendFormat("$('#{0}_{1}').click(function(){{{2}($);}});\n", controlId, attributeValue.Id, priceAdjustmentFuncName);
                        }
                    }
                    break;
                default:
                    break;
            }

        }
    }

    if (dynamicPriceUpdate && !hidePrices)
    {
        <script type="text/javascript">
            //Price adjustment table
            var @(priceAdjustmentTableName) = new Array();
            //Price adjustment table initialize
            @Html.Raw(priceAdjustmentTableScripts.ToString())
            //Price adjustment function
            function @(priceAdjustmentFuncName)($) {
                @if (dynamicPriceUpdateAjax)
                {
                    //load using AJAX
                    //this way we also load GTIN, SKU, MPN
                    var priceVarClass = string.Format("price-value-{0}", productId);

                    <text>
                $.ajax({
                    cache: false,
                    url: '@Url.Action("ProductDetails_AttributeChange", "ShoppingCart", new {productId = productId})',
                    data: $('#product-details-form').serialize(),
                    type: 'post',
                    success: function(data) {
                        if (data.sku) {
                            $('#sku-@productId').text(data.sku);
                        }
                        if (data.mpn) {
                            $('#mpn-@productId').text(data.mpn);
                        }
                        if (data.gtin) {
                            $('#gtin-@productId').text(data.gtin);
                        }
                        if (data.price) {
                            $(".@(priceVarClass)").text(data.price);
                        }
                    }
                });
                </text>
                }
                else
                {
                    //calculate new price using java-script (no AJAX)
                    var priceVarName = string.Format("priceValForDynUpd_{0}", productId);
                    var priceVarClass = string.Format("price-val-for-dyn-upd-{0}", productId);

                    <text>
                var sum = 0;
                for (var i in @(priceAdjustmentTableName)) {
                    var ctrl = $('#' + i);
                    // handler for Checkboxes, ReadonlyCheckboxes control type.
                    if ((ctrl.is(':radio') && ctrl.is(':checked')) || (ctrl.is(':checkbox') && ctrl.is(':checked'))) {
                        sum += @(priceAdjustmentTableName)[i];
                    } else if (ctrl.is("li") && ctrl.hasClass("selected")) {
                        sum += @(priceAdjustmentTableName)[i];
                    }
                }
                var res = (@(priceVarName) + sum).toFixed(2);
                $(".@(priceVarClass)").text(res);
                </text>
                }
            }
            //Price attributes handlers
            seajs.use("jquery", function($) {
                // hook dom ready events.
                $(function() {
                    // dom ready inmidately update product price if current item has selected and it has adjust price property.
                    @(priceAdjustmentFuncName)($);
                    @Html.Raw(priceAttributeScripts.ToString())
                });
            });
        </script>
    }
    @*productId attributes*@
    <div class="product-attributes">
        <ul class="list-unstyled">
            @foreach (var attribute in Model)
            {
                string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id);
                string textPrompt = !string.IsNullOrEmpty(attribute.TextPrompt) ? attribute.TextPrompt : attribute.Name;
                <li class="product-attributes-item">
                    <div class="product-attributes-title">
                        <label class="text-prompt">
                            @textPrompt
                        </label>
                        @if (attribute.IsRequired)
                        {
                            <span class="required">*</span>
                        }
                    </div>
                    <div class="product-attributes-value">
                        @switch (attribute.AttributeControlType)
                        {
                            case AttributeControlType.Checkboxes:
                            case AttributeControlType.ReadonlyCheckboxes:
                                {
                                    <ul class="option-list check-box-list">
                                        @foreach (var attributeValue in attribute.Values)
                                        {
                                            <li>
                                                <input id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null) />
                                                <label for="@(controlId)_@(attributeValue.Id)">@attributeValue.Name @(!String.IsNullOrEmpty(attributeValue.PriceAdjustment) ? " [" + attributeValue.PriceAdjustment + "]" : null)</label>
                                            </li>
                                        }
                                    </ul>
                                }
                                break;
                            case AttributeControlType.DropdownList:
                            case AttributeControlType.RadioList:
                            case AttributeControlType.ColorSquares:
                                {
                                    if (attribute.Values != null && attribute.Values.Count > 0)
                                    {
                                        // Only allow select one attribute.
                                        var attachedSelectedClass = false;
                                        var selectedValue = attribute.Values.FirstOrDefault(s => s.IsPreSelected);
                                        if (selectedValue == null)
                                        {
                                            selectedValue = attribute.Values[0];
                                            attribute.Values[0].IsPreSelected = true;
                                        }
                                        var isColorSquaresRgb = attribute.AttributeControlType == AttributeControlType.ColorSquares;
                                        bool hasPlacedSelected = false;
                                        <input type="hidden" value="@selectedValue.Id" name="@(controlId)" id="@(controlId)" />
                                        <ul class="option-list @(isColorSquaresRgb?"color-squares":"")" id="squares-@(attribute.Id)">
                                            @foreach (var attributeValue in attribute.Values)
                                            {
                                                // avoid multiple 'IsPreSelected=true'
                                                if (!hasPlacedSelected && attributeValue.IsPreSelected)
                                                {
                                                    hasPlacedSelected = true;
                                                }
                                                else if (hasPlacedSelected && attributeValue.IsPreSelected)
                                                {
                                                    attributeValue.IsPreSelected = false;
                                                }
                                                var adjustPrice = !String.IsNullOrEmpty(attributeValue.PriceAdjustment) ? " [" + attributeValue.PriceAdjustment + "]" : null;
                                                <li id="@(controlId)_@(attributeValue.Id)" title="@attributeValue.Name@adjustPrice" @(!attachedSelectedClass && attributeValue.IsPreSelected ? @Html.Raw(" class=\"selected\"") : Html.Raw("")) data-value="@attributeValue.Id">
                                                    <i></i>
                                                    @if (isColorSquaresRgb)
                                                    {
                                                        <span title="@attributeValue.Name@adjustPrice" style="background-color:@(attributeValue.ColorSquaresRgb);" class="pa_@(attributeValue.ColorSquaresRgb.Substring(1)) option-list-item">
                                                            &nbsp;
                                                        </span>
                                                    }
                                                    else
                                                    {
                                                        <span title="@attributeValue.Name@adjustPrice" class="option-list-item">
                                                            @attributeValue.Name
                                                        </span>
                                                    }
                                                </li>
                                            }
                                        </ul>
                                        <script type="text/javascript">
                                            seajs.use("jquery",function($) {
                                                $(function() {
                                                    $('.product-attributes').find("#squares-@(attribute.Id)").on('click', 'li', function(event) {
                                                        var $this = $(this);
                                                        var currSelectedId = $this.data("value");
                                                        var hiddenField = $this.parent("ul").prev("input[type='hidden']");
                                                        hiddenField.val(currSelectedId);
                                                        $this.addClass("selected").siblings("li").removeClass("selected");
                                                        // if enabled dynamic update price.
                                                        @if (dynamicPriceUpdate && !hidePrices)
                                                            {
                                                                @Html.Raw(priceAdjustmentFuncName+"($)");
                                                            }
                                                    });
                                                });
                                            });
                                        </script>
                                    }
                                }
                                break;
                        }
                    </div>
                </li>
            }
        </ul>
    </div>
}

